
package com.kweative.network;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

/**
 *
 * @author henrik
 */
public class HttpResponse extends Response {
    private LinkedList<HttpCookie> cookies = new LinkedList<HttpCookie>();

    public void addCookie(HttpCookie cookie) {
        cookies.add(cookie);
    }
    @Override
    public void write(OutputStream out) throws IOException {
        int code = 200;
        String msg = "Ok";
        switch(this.getStatus()) {
            case E_FORMAT:
                code = 400;
                msg = "Error in request formatting";
                break;
            case E_REQUEST:
                code = 400;
                msg = "Error in request";
                break;
            case E_NOTFOUND:
                code = 404;
                msg = "Requested ressource not found";
                break;
            case E_INTERNAL:
                code = 500;
                msg = "Internal error";
                break;
            case MOVED:
                code = 302;
                msg = "Permanent redirect";
                break;
                
        }
        out.write(String.format("HTTP/1.1 %s:%s\n",String.valueOf(code),msg).getBytes());
        if (cookies.size() > 0) {
            for(HttpCookie cookie:cookies) {
                headers().put("Set-Cookie",cookie.toString());
            }
        }
        this.headers().put("Content-length",String.valueOf(this.getBody().length));
        //this.headers().put("Connection","close");
        String header = "";
        for(Iterator<String> it = headers().keySet().iterator() ; it.hasNext();) {
            String key = it.next();
            header += String.format("%s:%s\n",key,headers().get(key));
        }
        out.write(header.getBytes());
        out.write("\n".getBytes());
        out.write(this.getBody());
    }
}
